<template>
  <el-dialog :close-on-click-modal="false" v-model="dialogVisible" width="500">
    <div class="flex_center_center">
      <span style="font-weight: bold; font-size: 28px">请扫描付款码支付</span>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="handleCancelPay">取消支付</el-button>
        <!-- <el-button type="primary" @click="dialogVisible = false">
          Confirm
        </el-button> -->
      </div>
    </template>
  </el-dialog>
  <div class="content" v-loading.fullscreen.lock="fullscreenLoading">
    <div
      v-show="fullscreenLoading"
      style="position: absolute; left: 47%; bottom: 40%; z-index: 999999999999"
    >
      <el-button type="danger" @click="handleInterrupt">中断支付</el-button>
    </div>
    <div
      v-show="printLoading"
      style="position: absolute; left: 46%; bottom: 40%; z-index: 999999999999"
    >
      <el-button type="success" disabled @click="handleInterrupt">
        正在打印小票
      </el-button>
    </div>
    <div class="left" v-loading.fullscreen.lock="printLoading">
      <el-dialog
        class="payDialog"
        v-model="dialogShow"
        :close-on-click-modal="false"
        title="现金支付"
        width="420"
      >
        <div class="title">应付: {{ totalCount.toFixed(2) }}元</div>
        <div class="user_pay">
          <div>实收:</div>
          <!-- <el-input-number
            ref="payRef"
            v-model.trim="userPay"
            :min="1"
            :max="5000"
            @change="handleChange"
          /> -->
          <el-input
            class="pay_ipt"
            ref="payRef"
            v-model.trim="userPay"
            @input="handleChange"
            keyboard="true"
          />
          <keyboard
            :transitionTime="'0.5s'"
            :maxQuantify="10"
            :showKeyboard="showKeyboard"
            @clickKey="clickKey"
            float
            :manyDict="manyDict"
            :singleDict="singleDict"
            @clickNumber="clickNumber"
            :blurHide="false"
          ></keyboard>
        </div>
        <div>找零: {{ userChange.toFixed(2) }} 元</div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleCloseDialog">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <el-input
        style="width: 0; height: 0; position: absolute; z-index: -99999999"
        @keyup.enter="debouncedHandleEnter"
        ref="iptRef"
        v-model="qrCode"
      />
      <el-tabs v-model="activeName" class="tabs" @tab-click="handleClick">
        <el-tab-pane name="pay">
          <template #label>
            <span class="tab_txt">收银</span>
          </template>
          <div class="item header">
            <div class="goods_img">商品照片</div>
            <div class="goods_name">商品名称</div>
            <div class="goods_price">单价(元)</div>
            <div class="goods_price">数量</div>
            <div class="total">小计(元)</div>
            <div class="action">操作</div>
          </div>
          <el-scrollbar height="67vh">
            <div
              class="item goods"
              v-for="(item, index) in goodsList"
              :key="index"
            >
              <div class="goods_img">
                <div class="img">
                  <img width="100%" height="100%" :src="item.image" alt="" />
                </div>
              </div>
              <div class="goods_name">
                <div class="title">{{ item.name }}</div>
                <div class="tip">{{ item.specifications }}</div>
              </div>
              <div class="goods_price">
                <div>
                  {{ formatNumber(item.price).integer }}
                  <span style="font-size: 14px; margin-left: -5px">
                    {{ formatNumber(item.price).decimal }}
                  </span>
                </div>
                <div class="vipPrice">
                  <div class="vipPrice_txt">会员价</div>
                  <div class="vipPrice_price">
                    {{ formatNumber(item.vip_price).integer }}
                    <span style="font-size: 12px; margin-left: -4px">
                      {{ formatNumber(item.vip_price).decimal }}
                    </span>
                  </div>
                </div>
              </div>
              <div class="goods_price">{{ item.count }}</div>
              <div class="total">
                <div>
                  {{
                    formatNumber((item.price * item.count).toFixed(2)).integer
                  }}
                  <span style="font-size: 14px; margin-left: -5px">
                    {{
                      formatNumber((item.price * item.count).toFixed(2)).decimal
                    }}
                  </span>
                </div>
                <div class="vipPrice">
                  <div class="vipPrice_txt">会员价</div>
                  <div class="vipPrice_price">
                    {{
                      formatNumber((item.vip_price * item.count).toFixed(2))
                        .integer
                    }}
                    <span style="font-size: 12px; margin-left: -4px">
                      {{
                        formatNumber((item.vip_price * item.count).toFixed(2))
                          .decimal
                      }}
                    </span>
                  </div>
                </div>
              </div>
              <div class="action" @click="handleDel(index)">
                <el-icon color="#D6DDE1" size="20">
                  <CircleCloseFilled />
                </el-icon>
              </div>
            </div>
          </el-scrollbar>
          <div class="footer">
            <div class="footer_left flex_center_center">
              <el-button
                :disabled="!goodsList.length > 0"
                class="btn"
                type="default"
                @click="handleHangOrder"
              >
                挂单
              </el-button>
            </div>
            <div class="footer_right flex_center_center">
              <span class="txt">
                <span style="font-size: 14px; margin-right: -4px"> ￥ </span>
                {{ formatNumber(totalCount.toFixed(2)).integer }}
                <span style="font-size: 16px; margin-left: -4px">
                  {{ formatNumber(totalCount.toFixed(2)).decimal }}
                </span>
              </span>
              <div class="vip_total">
                <div class="vip_total_txt flex_center">会员价</div>
                <div class="vip_total_price">
                  <span
                    style="
                      font-size: 14px;
                      margin-left: 4px;
                      margin-right: -4px;
                    "
                  >
                    ￥
                  </span>
                  {{ formatNumber(totalCountVip.toFixed(2)).integer }}
                  <span style="font-size: 16px; margin-left: -4px">
                    {{ formatNumber(totalCountVip.toFixed(2)).decimal }}
                  </span>
                </div>
              </div>
              <el-popover
                ref="popref"
                placement="top-end"
                width="15vw"
                :visible="payShow"
                effect="dark"
              >
                <div
                  class="popover_card flex_space_between"
                  @click="debouncedHandlePay(item)"
                  v-for="(item, index) in payList"
                  :key="index"
                >
                  <div class="popover_item_icon">
                    <img
                      v-if="item.type == 'cash'"
                      src="../../assets/images/cashier/ye.png"
                      alt=""
                    />
                    <img
                      v-else-if="item.type == 'zfb'"
                      src="../../assets/images/cashier/zfb.png"
                      alt=""
                    />
                    <img
                      v-else-if="item.type == 'wx'"
                      src="../../assets/images/cashier/wx.png"
                      alt=""
                    />
                    <img
                      v-else
                      src="../../assets/images/cashier/Frame.png"
                      alt=""
                    />
                  </div>
                  <div class="popover_item_txt">
                    {{ item.name }}
                  </div>
                </div>

                <template #reference>
                  <el-button
                    :disabled="!goodsList.length"
                    @click="payShow = true"
                    color="#FD6013"
                    class="finish_btn"
                    type="default"
                    >结算({{ totalNum }})</el-button
                  >
                </template>
              </el-popover>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane class="pending_order" name="take">
          <template #label>
            <span class="tab_txt">挂单</span>
            <div class="tab_num flex_center_center">
              <span class="txt">{{ hangOrderList.length }}</span>
            </div>
          </template>
          <div class="pending_order_left">
            <el-button
              :icon="Delete"
              color="#eef2f5"
              class="clear_btn"
              type="primary"
              @click="handleClickAll"
              >一键清空
            </el-button>
            <div
              class="order_card"
              v-for="(item, index) in hangOrderList"
              :key="index"
              :class="{ selected: selectedCard === index }"
              @click="selectCard(item, index)"
            >
              <div class="order_name">订单&nbsp;{{ index + 1 }}</div>
              <div class="order_price">
                <span class="txt">￥{{ item.totalCount.toFixed(2) }}</span>
                <el-icon
                  v-show="selectedCard === index"
                  @click.stop.prevent="handleDelOrder(index)"
                  color="#EB5E12"
                  size="14"
                >
                  <DeleteFilled />
                </el-icon>
              </div>
            </div>
          </div>

          <div class="pending_order_right">
            <div class="item header">
              <div class="goods_img">商品照片</div>
              <div class="goods_name">商品名称</div>
              <div class="goods_price">单价(元)</div>
              <div class="goods_price">数量</div>
              <div class="total">小计</div>
              <div class="action">操作</div>
            </div>
            <el-scrollbar height="67vh">
              <div
                class="item goods"
                v-for="(item, index) in goodsList"
                :key="index"
              >
                <div class="goods_img">
                  <div class="img">
                    <img width="100%" height="100%" :src="item.image" alt="" />
                  </div>
                </div>
                <div class="goods_name">
                  <div class="title">
                    {{ item.name }}{{ item.name }}{{ item.name }}{{ item.name }}
                  </div>
                  <div class="tip">{{ item.specifications }}</div>
                </div>
                <div class="goods_price">
                  <div>
                    {{ formatNumber(item.price).integer }}
                    <span style="font-size: 14px; margin-left: -5px">
                      {{ formatNumber(item.price).decimal }}
                    </span>
                  </div>
                  <div class="vipPrice_hang">
                    <div class="vipPrice_txt_hang">会员价</div>
                    <div class="vipPrice_price_hang">
                      {{ formatNumber(item.vip_price).integer }}
                      <span style="font-size: 10px; margin-left: -4px">
                        {{ formatNumber(item.vip_price).decimal }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="goods_price">{{ item.count }}</div>
                <div class="total">
                  <div>
                    {{
                      formatNumber((item.price * item.count).toFixed(2)).integer
                    }}
                    <span style="font-size: 14px; margin-left: -5px">
                      {{
                        formatNumber((item.price * item.count).toFixed(2))
                          .decimal
                      }}
                    </span>
                  </div>
                  <div class="vipPrice_hang">
                    <div class="vipPrice_txt_hang">会员价</div>
                    <div class="vipPrice_price_hang">
                      {{
                        formatNumber((item.vip_price * item.count).toFixed(2))
                          .integer
                      }}
                      <span style="font-size: 10px; margin-left: -4px">
                        {{
                          formatNumber((item.vip_price * item.count).toFixed(2))
                            .decimal
                        }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="action" @click="handleDel(index)">
                  <el-icon color="#D6DDE1" size="20">
                    <CircleCloseFilled />
                  </el-icon>
                </div>
              </div>
            </el-scrollbar>
            <div class="footer">
              <div class="footer_left flex_center_center">
                <!-- <el-button class="btn" type="default" @click="handleHangOrder">
                  挂单
                </el-button> -->
                <!-- <el-button class="btn" type="default">取单</el-button> -->
              </div>
              <div class="footer_right flex_center_center">
                <span class="txt">
                  <span style="font-size: 16px; margin-right: -4px">￥</span>
                  {{ formatNumber(totalCount.toFixed(2)).integer }}
                  <span style="font-size: 16px; margin-left: -4px">
                    {{ formatNumber(totalCount.toFixed(2)).decimal }}
                  </span>
                </span>
                <div class="vip_total">
                  <div class="vip_total_txt flex_center">会员价</div>
                  <div class="vip_total_price">
                    <span
                      style="
                        font-size: 16px;
                        margin-left: 4px;
                        margin-right: -4px;
                      "
                      >￥</span
                    >
                    {{ formatNumber(totalCountVip.toFixed(2)).integer }}
                    <span style="font-size: 16px; margin-left: -4px">
                      {{ formatNumber(totalCountVip.toFixed(2)).decimal }}
                    </span>
                  </div>
                </div>
                <el-popover
                  ref="popref"
                  placement="top-end"
                  width="15vw"
                  trigger="click"
                  effect="dark"
                >
                  <div
                    class="popover_card flex_space_between"
                    @click.stop.prevent="debouncedHandlePay(item)"
                    v-for="(item, index) in payList"
                    :key="index"
                  >
                    <div class="popover_item_icon">
                      <img
                        v-if="item.type == 'cash'"
                        src="../../assets/images/cashier/ye.png"
                        alt=""
                      />
                      <img
                        v-else-if="item.type == 'zfb'"
                        src="../../assets/images/cashier/zfb.png"
                        alt=""
                      />
                      <img
                        v-else-if="item.type == 'wx'"
                        src="../../assets/images/cashier/wx.png"
                        alt=""
                      />
                      <img
                        v-else
                        src="../../assets/images/cashier/Frame.png"
                        alt=""
                      />
                    </div>
                    <div class="popover_item_txt">
                      {{ item.name }}
                    </div>
                  </div>

                  <template #reference>
                    <el-button
                      :disabled="!goodsList.length"
                      color="#FD6013"
                      class="finish_btn"
                      type="default"
                      >结算({{ totalNum }})</el-button
                    >
                  </template>
                </el-popover>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane name="get">
          <template #label>
            <span class="tab_txt">结单</span>
            <div class="tab_num flex_center_center">
              <span class="txt">1</span>
            </div>
          </template>
        </el-tab-pane> -->
      </el-tabs>
    </div>
    <div @click="printPdf" id="invoice" class="invoice" style="display: none">
      <div class="logo">
        <img width="270px" :src="printData.logo_img" alt="" />
      </div>
      <div class="details">
        <p style="font-size: 12px; margin-left: 40px">
          {{ printData.logo_title }}
        </p>
        <div style="font-size: 12px">订单号：{{ printData.sn }}</div>
        <div style="font-size: 12px">交易时间：{{ printData.time }}</div>
        <div style="font-size: 12px">终端：{{ printData.code }}</div>
      </div>
      <div
        style="
          height: 1px;
          width: 400px;
          border-bottom: 1px dashed black;
          margin-top: 10px;
          margin-bottom: 10px;
        "
      ></div>
      <div style="display: flex; font-size: 12px; font-weight: bold">
        <div style="width: 6%">商品</div>
        <div style="width: 2.5%; text-align: center">数量</div>
        <div style="width: 2.5%; text-align: center">单价</div>
        <div style="width: 2.5%; text-align: center">总价</div>
      </div>
      <div
        style="display: flex; font-size: 12px"
        v-for="(item, index) in printData.item"
        :key="index"
      >
        <div style="width: 6%">{{ item.goods_title }}</div>
        <div style="width: 2.5%; text-align: center">{{ item.goods_num }}</div>
        <div style="width: 2.5%; text-align: center">
          {{ item.goods_price }}
        </div>
        <div style="width: 2.5%; text-align: center">{{ item.pay_fee }}</div>
      </div>
      <div style="display: flex; margin-top: 10px; font-size: 12px">
        <div style="width: 11%">合计：</div>
        <div>{{ printData.order_amount }}</div>
      </div>
      <div
        style="
          height: 1px;
          width: 400px;
          border-bottom: 1px dashed black;
          margin-top: 10px;
          margin-bottom: 10px;
        "
      ></div>

      <div style="display: flex; margin-top: 10px; font-size: 12px">
        <div style="width: 11%">支付类型</div>
        <div>
          {{ printData.pay_type }}
        </div>
      </div>
      <div style="display: flex; font-size: 12px">
        <div style="width: 11%">支付金额</div>
        <div>{{ printData.order_amount }}</div>
      </div>
      <div style="display: flex; font-size: 12px">
        <div style="width: 11%">实付</div>
        <div>{{ printData.pay_fee }}</div>
      </div>
      <div style="display: flex; font-size: 12px">
        <div style="width: 11%">找零</div>
        <div>{{ printData.zl_price || "-" }}</div>
      </div>

      <div
        style="
          height: 1px;
          width: 400px;
          border-bottom: 1px dashed black;
          margin-top: 10px;
          margin-bottom: 10px;
        "
      ></div>

      <p style="font-size: 12px; margin-left: 75px">
        {{ printData.code_title }}
      </p>
      <div style="margin-left: 78px">
        <img width="120px" :src="printData.code_img" alt="" />
      </div>
      <div style="margin-top: 30px; font-size: 12px; margin-left: 65px">
        {{ printData.store_mobile }}
      </div>
      <div style="font-size: 12px; margin-left: 75px">
        {{ printData.store_title }}
      </div>
      <div style="font-size: 12px; margin-left: 40px">
        {{ printData.store_site }}
      </div>
      <!-- <div class="qr-code">
        <img src="@/assets/imgs/avatar.jpg" alt="QR Code" />
      </div> -->
    </div>
    <div class="right">
      <div class="right_header">
        <div
          class="right_header_item flex_center_center"
          v-for="(item, index) in userState.userInfo.goods"
          :key="index"
          :class="{ tagSelected: selectedTag === index }"
          @click="selectTag(index)"
        >
          <span>{{ item.classification }}</span>
        </div>
      </div>

      <div class="">
        <el-scrollbar height="100%">
          <div class="right_content">
            <div
              class="right_content_item"
              v-for="(tagItem, tagIndex) in userState.userInfo.goods[
                selectedTag
              ].goods_list"
              :key="tagIndex"
              @click="handleAdd(tagItem)"
            >
              <div class="right_content_img">
                <img width="100%" height="100%" :src="tagItem.image" alt="" />
              </div>
              <div class="right_content_name">{{ tagItem.name }}</div>
              <div class="right_content_price">￥{{ tagItem.price }}</div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  watchEffect,
  ref,
  reactive,
  nextTick,
  onMounted,
  computed,
  watch,
  h,
  onUnmounted,
} from "vue";
import { Delete, DeleteFilled } from "@element-plus/icons-vue";
import { ElInput, ElMessage } from "element-plus";
import {
  getGoodsByCode,
  createOrder,
  printOrder,
} from "../../api/cashier/index";
import { reqPullPay } from "../../api/order/index";
import { getLodop } from "../../utils/LodopFuncs.js";
import { useUserStore } from "../../store/modules/user";
import { debounce, useFormattedNumber } from "../../utils/common.js";
import keyboard from "../../components/keyboard/keyboardIndex.vue";

// 输入框失焦处理
const handleIptBlur = async () => {
  // if (!dialogShow.value && document.activeElement !== iptRef.value) {
  //   await nextTick();
  //   iptRef.value?.focus();
  // }
  // await nextTick();
  // if (!dialogShow.value) {
  //   iptRef.value?.focus();
  // } else {
  //   payRef.value?.focus();
  // }
};

// 失焦轮训
let focusInterval;
// 支付轮训
let currentPaymentTimer = [];

// 设置定时器，每100ms检查一次并聚焦输入框
const setupFocusInterval = () => {
  focusInterval = setInterval(() => {
    if (!dialogShow.value && document.activeElement !== iptRef.value) {
      iptRef.value?.focus();
    }
  }, 100);
};

onMounted(() => {
  setupFocusInterval();
});

onUnmounted(() => {
  if (currentPaymentTimer) {
    currentPaymentTimer.forEach((timerId) => {
      clearTimeout(timerId);
    });
  }
  currentPaymentTimer = [];
  if (focusInterval) {
    clearInterval(focusInterval);
  }
  if (abortController) {
    abortController.abort();
    abortController = null;
  }
});

const dialogVisible = ref(false);
// 取消支付
const handleCancelPay = () => {
  dialogVisible.value = false;
  scanFlag.value = true;
};

const { formatNumber } = useFormattedNumber();

/**
 * @软键盘相关
 */
const showKeyboard = ref(false);
const clickKey = (key) => {};
const clickNumber = (key) => {};
const manyDict = ref("dict/chowder.json");
const singleDict = ref("dict/baseDict.json");

// 用户信息仓库
const userState = useUserStore();

// lodop => 打印
const printPdf = (e) => {
  let LODOP = getLodop();
  if (!LODOP) {
    console.error("");
    return;
  }
  LODOP.PRINT_INIT("标签");
  LODOP.SET_PRINT_STYLE("FontSize", 16);
  LODOP.SET_PRINT_STYLE("Bold", 1);

  LODOP.SET_PRINT_PAGESIZE(3, 1200, 0, "");
  LODOP.SET_PREVIEW_WINDOW(0, 0, 0, 800, 800, "");

  let printHtml = document.getElementById("invoice")?.innerHTML;
  if (!printHtml) {
    console.error("1");
    return;
  }
  LODOP.ADD_PRINT_HTM(0, 0, 1980, 2870, printHtml);
  LODOP.SET_PRINT_STYLEA(0, "QRCodeErrorLevel", "M");
  LODOP.SET_PRINT_STYLEA(0, "AlignJustify", 2);

  LODOP.PRINT();

  if (e) {
    LODOP.SEND_PRINT_RAWDATA(String.fromCharCode(27, 112, 0, 25, 250));
  }

  // LODOP.PRINT_DESIGN();
  // LODOP.PREVIEW();
};

// 扫描标记 => 判断扫商品或扫付款码
const scanFlag = ref(true);

// 扫码框以及找零框ref
const iptRef = ref();
const payRef = ref(null);
const userPay = ref(0);
const dialogShow = ref(false);
const userChange = ref(0);

// 监听支付弹框显示或隐藏 => 聚焦对应输入框
watchEffect(async () => {
  // console.log(dialogShow.value);
  await nextTick();
  if (dialogShow.value === false) {
    iptRef.value?.focus();
  } else {
    payRef.value?.focus();
  }
});

// 打印数据
const printData = ref({});
const printLoading = ref(false);

// 关闭对话框处理
const handleCloseDialog = async () => {
  // 提交支付时,传应付金额和找零金额  支付>应付才传
  const payParams = {
    ...payParam.value,
  };

  if (userPay.value > totalCount.value) {
    // 传找零金额
    payParams.ood_price = userChange.value;
    // payParams.receipts_price = userChange.value;
  }

  const payRes = await reqPullPay(payParams);
  if (payRes.code === 1) {
    ElMessage(payRes.msg);
  }
  dialogShow.value = false;
  userPay.value = 0;
  try {
    const res = await printOrder(payStatusParam.value);
    if (res.code == 1) {
      printData.value = res.data;
      printLoading.value = true;
    }
    nextTick(() => {
      printPdf("cash");
    });
  } finally {
    setTimeout(() => {
      printLoading.value = false;
    }, 1500);
    goodsList.length = 0;
    hangOrderList.value.splice(hangOrderIndex.value, 1);
    localStorage.setItem("hangOrderList", JSON.stringify(hangOrderList));
    hangOrderIndex.value = null;
  }
};

// 商品列表
const goodsList = reactive([]);

// 二维码
const qrCode = ref("");

// 扫码枪扫码后自动按一次回车 => 处理回车事件
const handleEnter = () => {
  if (scanFlag.value === true) {
    scanAddGoods();
  } else if (scanFlag.value === false) {
    debouncedHandlePayEnter();
  }
};

// 扫码添加商品
const scanAddGoods = async () => {
  const formData = {
    coding: qrCode.value,
    code: "vX7kYhyEVqOcFWJn",
  };

  try {
    const res = await getGoodsByCode(formData);
    if (res.code === 0) {
      ElMessage.error("请扫描正确的条码！");
      qrCode.value = "";
    } else if (res.data) {
      ElMessage.success("添加商品成功！");
      res.data.count = 1;
      res.data.codings = [res.data.coding];

      if (res.data.is_code === 0) {
        // 如果 is_code 为 0,直接增加数量,不检查重复
        const existingItem = goodsList.find(
          (item) => item.goods_id === res.data.goods_id
        );
        if (existingItem) {
          existingItem.count++;
        } else {
          goodsList.push(res.data);
        }
      } else {
        // 我们自己的条码
        const existingItemByIdAndCoding = goodsList.find((item) => {
          return (
            item.goods_id === res.data.goods_id &&
            item.codings &&
            item.codings.includes(res.data.coding)
          );
        });

        const existingItemByIdAndDifferentCoding = goodsList.find((item) => {
          return (
            item.goods_id === res.data.goods_id &&
            (!item.codings || !item.codings.includes(res.data.coding))
          );
        });

        if (existingItemByIdAndCoding) {
          ElMessage.error("商品重复！");
        } else if (existingItemByIdAndDifferentCoding) {
          existingItemByIdAndDifferentCoding.count++;
          existingItemByIdAndDifferentCoding.codings.push(res.data.coding);
        } else {
          goodsList.push(res.data);
        }
      }

      qrCode.value = "";
      localStorage.setItem("goodsList", JSON.stringify(goodsList));
    } else {
      console.log(res.data);
    }
  } catch (error) {
    console.error(error);
  }
};

// 防抖处理回车事件
const debouncedHandleEnter = debounce(handleEnter, 0);

// 添加商品
const handleAdd = (rightGoods) => {
  const newGood = { ...rightGoods, count: 1, right: 1 };

  const existingItemIndex = goodsList.findIndex(
    (item) => item.name === rightGoods.name
  );

  if (existingItemIndex !== -1) {
    goodsList[existingItemIndex].count++;
  } else {
    goodsList.push(newGood);
  }
  localStorage.setItem("goodsList", JSON.stringify(goodsList));
};

// 计算总数量和总价
const totalNum = computed(() => goodsList.length);
const totalCount = computed(() => {
  return goodsList.reduce((sum, item) => sum + item.count * item.price, 0);
});

const totalCountVip = computed(() => {
  return goodsList.reduce((sum, item) => sum + item.count * item.vip_price, 0);
});

// 删除商品
const handleDel = (index) => {
  goodsList.splice(index, 1);
  localStorage.setItem("goodsList", JSON.stringify(goodsList));
};

// 挂单列表
const storedHangOrderList = JSON.parse(localStorage.getItem("hangOrderList"));
const hangOrderList = ref(
  Array.isArray(storedHangOrderList) ? storedHangOrderList : []
);

// 监听挂单列表变化
watch(
  hangOrderList,
  (newList) => {
    localStorage.setItem("hangOrderList", JSON.stringify(newList));
  },
  { deep: true }
);

// 挂单处理
const handleHangOrder = () => {
  const order = {
    goods: [...goodsList],
    totalCount: totalCount.value,
    totalNum: totalNum.value,
  };
  hangOrderList.value.push(order);
  localStorage.setItem("hangOrderList", JSON.stringify(hangOrderList.value));
  goodsList.length = 0;
  localStorage.setItem("goodsList", JSON.stringify(goodsList));
};

// 删除单条挂单
const handleDelOrder = (index) => {
  hangOrderList.value.splice(index, 1);
  localStorage.setItem("hangOrderList", JSON.stringify(hangOrderList));
  goodsList.length = 0;
  localStorage.setItem("goodsList", JSON.stringify(goodsList));
};

// 清空所有挂单
const handleClickAll = () => {
  hangOrderList.value.length = 0;
  localStorage.setItem("hangOrderList", JSON.stringify(hangOrderList.value));
  goodsList.length = 0;
};

/**
 * @支付相关
 */
const activeName = ref("pay");
const payShow = ref(false); // 支付方式列表
const payList = reactive([
  {
    name: "现金",
    icon: "../../assets/images/cashier/ye.png",
    type: "cash",
  },
  {
    name: "微信",
    icon: "../../assets/images/cashier/wx.png",
    type: "wx",
  },
  {
    name: "支付宝",
    icon: "../../assets/images/cashier/zfb.png",
    type: "zfb",
  },
  {
    name: "会员余额",
    icon: "../../assets/images/cashier/Frame.png",
    type: "vip",
  },
]);

const selectedTag = ref(0);

const selectTag = (index) => {
  selectedTag.value = index;
};

// 选择挂单
const hangOrderIndex = ref();
const selectedCard = ref(0);
const selectCard = (item, index) => {
  hangOrderIndex.value = index;
  selectedCard.value = index;
  goodsList.splice(0, goodsList.length, ...item.goods);
  localStorage.setItem("goodsList", JSON.stringify(goodsList));
};

// tab切换时清空列表 => 聚焦扫码输入框
const handleClick = (tab, event) => {
  goodsList.length = 0;
  focusOnInput();
};

// 支付参数
const payParam = ref({
  id: "",
  code: "vX7kYhyEVqOcFWJn",
  pay_type: "",
  auth_code: "",
});

const payStatusParam = ref({
  id: "",
  code: userState.userInfo.code,
});

// 找零 => 处理金额变化
const handleChange = (e) => {
  console.log(userPay.value);
  if (userPay.value > totalCount.value) {
    userChange.value = userPay.value - totalCount.value;
  } else {
    userChange.value = 0;
    // ElMessage.error("请输入正确的金额！实付金额不能小于应收金额！");
  }
};

// 创建订单
const handleCreateOrder = async (type) => {
  // console.log(scanFlag.value, "创建订单");
  const data = JSON.parse(localStorage.getItem("goodsList"));
  const itemsMap = {};

  data.forEach((item) => {
    if (!itemsMap[item.id]) {
      itemsMap[item.id] = {
        ...item,
        num: item.count,
        goods_id: item.id,
        type: item.right === 1 ? 0 : 1,
      };

      if (item.right !== 1) {
        itemsMap[item.id].id = [item.coding];
      }
    } else {
      itemsMap[item.id].num += item.count;
      if (item.right !== 1) {
        itemsMap[item.id].id.push(item.coding);
      }
    }
  });

  // TODO:这里要做如果是会员支付的话改结算价格都是会员价
  const createFormData = Object.values(itemsMap);

  const formData = {
    code: "vX7kYhyEVqOcFWJn",
    data: createFormData,
  };
  try {
    const res = await createOrder(formData);
    if (res.code === 1) {
      payStatusParam.value.id = res.data;
      payParam.value.id = res.data;
      ElMessage(res.msg);
      if (type == "cash") {
        dialogShow.value = true;
        scanFlag.value = true;
        userPay.value = totalCount.value.toFixed(2);
      } else {
        dialogVisible.value = true;
      }
    } else {
      ElMessage.error(res.msg || "订单创建失败");
    }
  } catch (e) {
    console.log(e);
  }
};

// 处理支付
const handlePay = async (item) => {
  payShow.value = false;
  handleCreateOrder(item.type);
  scanFlag.value = false;
  payParam.value.pay_type = item.type;
};

// 支付 => +防抖
const debouncedHandlePay = debounce(handlePay, 300);
const fullscreenLoading = ref(false);

// 扫付款码时 => 回车事件
// 是否继续支付
let isPaymentCancelled = false;
let abortController = null; // 阻断请求
// 扫付款码时 => 回车事件
const handlePayEnter = debounce(async () => {
  // 清除之前的定时器（如果存在）
  fullscreenLoading.value = true;
  if (currentPaymentTimer.length != 0) {
    currentPaymentTimer.forEach((timerId) => {
      clearTimeout(timerId);
    });
    currentPaymentTimer = [];
  }

  // 如果存在之前的 abortController，则取消之前的请求
  if (abortController) {
    abortController.abort();
  }

  isPaymentCancelled = false;
  abortController = new AbortController();
  payParam.value.auth_code = qrCode.value;
  qrCode.value = "";

  const pullPay = async (attemptCount = 0) => {
    if (isPaymentCancelled) {
      fullscreenLoading.value = false;
      return; // 如果支付被取消，直接返回
    }

    if (attemptCount >= 20) {
      // 达到最大尝试次数
      fullscreenLoading.value = false;
      ElMessage.error("支付超时，请重试");
      dialogVisible.value = false;
      scanFlag.value = true;
      return;
    }

    const result = await reqPullPay(payParam.value, abortController.signal);

    // 再次检查是否已取消
    if (isPaymentCancelled) {
      fullscreenLoading.value = false;
      return;
    }

    if (result.code != 1) {
      // 继续尝试
      ElMessage.error(result.msg);
      // 使用全局变量保存定时器 ID
      currentPaymentTimer.push(
        setTimeout(() => pullPay(attemptCount + 1), 1000)
      ); // 每1秒尝试一次
    } else {
      // 支付成功
      ElMessage.success(result.msg);
      dialogVisible.value = false;
      payShow.value = false;
      fullscreenLoading.value = false;
      hangOrderList.value.splice(hangOrderIndex.value, 1);
      localStorage.setItem(
        "hangOrderList",
        JSON.stringify(hangOrderList.value)
      );
      hangOrderIndex.value = null;
      scanFlag.value = true;
      qrCode.value = "";
      try {
        const res = await printOrder(payStatusParam.value);
        if (res.code == 1) {
          printLoading.value = true;
          printData.value = res.data;
        }
        nextTick(() => {
          printPdf();
        });
      } finally {
        setTimeout(() => {
          printLoading.value = false;
        }, 1500);
        goodsList.length = 0;
      }
    }
  };

  pullPay(); // 开始尝试支付
}, 500);

// 支付中 => 中断支付
const handleInterrupt = () => {
  dialogVisible.value = false;
  scanFlag.value = true;
  currentPaymentTimer.forEach((timerId) => {
    clearTimeout(timerId);
  });
  currentPaymentTimer = [];
  isPaymentCancelled = true;
  if (abortController) {
    abortController.abort(); // 取消正在进行的请求
  }
  fullscreenLoading.value = false;
};

// 给扫付款吗 => +回车
const debouncedHandlePayEnter = debounce(handlePayEnter, 300);
</script>

<style lang="scss" scoped>
@import "../../assets/style/common";
@import "../../assets/style/cashier";

.invoice {
  width: 200px;
  padding: 10px;
  border: 1px solid #000;
  margin: 0 auto;
}
.logo {
  text-align: center;
  margin-bottom: 10px;
}
.logo img {
  width: 80px;
}
.details,
.footer {
  font-size: 10px;
  margin-bottom: 10px;
}
.details {
  line-height: 1.5;
}
.items {
  width: 100%;
  margin-bottom: 10px;
}
.items th,
.items td {
  border-bottom: 1px solid #000;
  padding: 5px;
  font-size: 10px;
  text-align: left;
}
.items th {
  font-weight: bold;
}
.items td {
  font-size: 10px;
}
.qr-code {
  text-align: center;
  margin-top: 10px;
}
.qr-code img {
  width: 80px;
  height: 80px;
}

.content {
  width: 100%;
  height: 90vh;
  display: flex;
  justify-content: space-between;

  .left,
  .right {
    border-radius: $box-radius;
    height: 100%;
  }

  .left {
    width: 65%;
    background-color: white;
    padding: 0 1vw;

    .header {
      padding-left: 0.8vw;
      font-weight: 400;
      font-size: 14px;
      color: #999999;
      height: 3vh;
      margin-bottom: 10px;
      border-top: none !important;
    }

    .goods {
      padding: 0.8vw 0.8vw 0 0.8vw;
      font-weight: 800;
      font-size: 0.8vw;
      color: #333333;

      .goods_price,
      .total,
      .action {
        font-size: $main-font-size;
        text-indent: 0.5rem;
      }

      .action {
        padding-left: 12px;
      }

      .tip {
        margin-top: 0.5vh;
        font-weight: 400;
        font-size: $main-list-font-size;
        color: #999999;
      }
    }

    .item {
      display: flex;
      border-top: 1px solid #eef2f5;

      .goods_price,
      .total,
      .action {
        width: 14%;
        height: 7vh;
        //font-size: $main-font-size;
      }

      .goods_img {
        display: flex;
        width: 10%;

        .img {
          width: 57%;
          height: 75%;
          background-color: skyblue;
        }
      }

      .goods_name {
        flex: 1;
        margin-right: 2vw;

        .title {
          font-size: $main-font-size;
          overflow: hidden;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          /* 限制显示的行数 */
          white-space: normal;
        }
      }
    }

    .footer {
      padding: 0 0.8vw 0 0.8vw;
      border-top: 1px solid #f2efef;
      height: 9.1vh;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .footer_left {
        .btn {
          width: 6vw;
          font-size: 1vw;
        }
      }

      .footer_right {
        .txt {
          margin-right: 1vw;
          font-weight: bold;
          font-size: 20px;
          color: #333333;
        }

        .finish_btn {
          font-weight: 400;
          font-size: 14px;
          color: #ffffff;
          letter-spacing: 1px;
          margin-left: 1vw;
        }
      }
    }

    .pending_order {
      display: flex;

      .pending_order_left {
        width: 35%;
        //height: 100%;
        margin-right: 2%;
        background-color: #eef2f5;
        border-radius: $box-radius;
        padding: 1vw 0.8vw;

        .clear_btn {
          border: 1px solid #d4d6d9;
          width: 100%;
          color: #666666;
        }

        .order_card {
          border-radius: $box-radius;
          background: white;
          display: flex;
          justify-content: space-between;
          padding: 0.8vw;
          margin-top: 1.5vh;
          font-weight: 800;
          font-size: 1vw;
          color: #333333;
          border: 1px solid white;

          .order_price {
            display: flex;
            align-items: center;

            .txt {
              margin-right: 0.5vw;
            }
          }
        }

        .selected {
          background: #fff7f4;
          border: 1px solid #fd6013;
          box-shadow: 0px 1px 5px 0px rgba(207, 196, 191, 0.6);
        }
      }

      .pending_order_right {
        height: 100%;
        width: 63%;

        .item {
          display: flex;

          .goods_img,
          .goods_price,
          .total,
          .action {
            width: 15%;
            height: 7vh;
          }

          .goods_img {
            display: flex;

            .img {
              width: 60%;
              height: 80%;
              background-color: skyblue;
            }
          }

          .goods_name {
            flex: 1;
            margin-right: 2vw;

            .title {
              font-size: $main-font-size;
            }
          }
        }
      }
    }
  }

  .right {
    width: 34%;
    height: 99.9%;

    .right_header,
    .right_content {
      border-radius: $box-radius;
    }

    .right_header {
      background-color: white;
      height: 8.5%;
      margin-bottom: 0%;
      padding: 1vw;
      display: flex;
      flex-wrap: wrap;

      .right_header_item {
        font-size: 12px;
        height: 4vh;
        padding: 0 1.2vw;
        border-radius: $box-radius;
        border: 1px solid #d4d6d9;
        margin-right: 0.8vw;
        margin-bottom: 0.8vw;
      }

      .tagSelected {
        border: none;
        background-color: #2f51ff;
        color: white;
      }
    }

    .right_content {
      width: 100%;
      height: 91%;
      display: flex;
      flex-wrap: wrap;
      // justify-content: space-between;

      .right_content_item {
        border: 1px solid white;
        background-color: white;
        padding: 7px;
        width: 32%;
        height: 32.1%;
        border-radius: $box-radius;
        margin-top: 2%;
        margin-right: 2%;

        &:nth-child(3n) {
          margin-right: 0;
        }

        .right_content_img {
          width: 99%;
          height: 135px;
          background-color: #d9d9d9;
          border-radius: $box-radius;
        }

        .right_content_name,
        .right_content_price {
          overflow: hidden;
          //height: 2vh;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          /* 限制显示的行数 */
          white-space: normal;
          font-weight: 800;
          font-size: 14px;
          color: #333333;
        }

        .right_content_name {
          margin-top: 4.5px;
        }

        .right_content_price {
          margin-top: 0.3vw;
        }
      }

      .right_content_item:hover {
        border: 1px solid #fd6013;
        box-shadow: 0px 3px 11px 0px rgba(133, 133, 133, 0.4);
        cursor: pointer;
      }
    }
  }
}
</style>
